<template>
  <div id="goodDetail">
    <van-tabs v-model="tabActive" scrollspy sticky>
      <van-tab  title="商品">
        <van-image width="100%" height="200px" :src="goodDetail.primary_pic_url" />
        
        <van-cell title="已选" :value="selectGood" clickable is-link center @click="onClickSelectGood" />
        
        <van-sku
          v-model="showSku"
          :sku="sku"
          :goods="goods"
          :goods-id="goodDetail.id"
          :quota="3"
          :quota-used="1"
          :hide-stock="false"
          :initial-sku="initialSku"
          @buy-clicked="onBuyClicked"
          @add-cart="onAddCartClicked"
          @sku-selected="onSelectSku"
          ref="sku"
        />
        
        <van-goods-action>
          <van-goods-action-icon icon="chat-o" text="客服" color="#07c160" to="/customer" />
          <van-goods-action-icon :badge="cart_num" icon="cart-o" text="购物车" to="/cart" />
          <van-goods-action-icon :icon="isCollected?'star':'star-o'" :text="isCollected?'已收藏':'收藏'" color="#ff5000" @click="onClickCollect" />
          <van-goods-action-button type="warning" text="加入购物车" @click="onAddCartClicked" />
          <van-goods-action-button type="danger" text="立即购买" @click="onBuyClicked" />
        </van-goods-action>
      </van-tab>
      <van-tab  title="评价">
        <van-divider :style="{color: 'red', borderColor: 'red'}">评价</van-divider>
        <van-empty
          class="custom-image"
          image="https://img.yzcdn.cn/vant/custom-empty-image.png"
          description="没有评价"
        />
      </van-tab>
      <van-divider :style="{color: 'red', borderColor: 'red'}">详情</van-divider>
      <van-tab  title="详情">
        <div class="goods-desc" v-html="goodDetail.goods_desc"></div>
        <div>商品参数</div>
        <van-divider />
        <van-row type="flex" v-for="(item,index) in goodDetail.goodsAttribute" :key="index">
          <van-col span="12" style="backgroundColor: #e7e3e3; border: 2px solid #8f8c8c; padding: 5px; margin: 1px;">
            {{item.attribute&&item.attribute.name}}
          </van-col>
          <van-col span="12" style="backgroundColor: #e7e3e3; border: 2px solid #8f8c8c; padding: 5px; margin: 1px;">
            {{item.value}}
          </van-col>
        </van-row>
      </van-tab>
      <van-tab  title="推荐">
        <van-divider :style="{color: 'red', borderColor: 'red'}">推荐</van-divider>
        <van-empty
          class="custom-image"
          image="https://img.yzcdn.cn/vant/custom-empty-image.png"
          description="没有推荐商品"
        />
      </van-tab>
    </van-tabs>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  #goodDetail{
    width: 100%;
    height: 100%;
    text-align: left;
  }
  /deep/.goods-desc{
    width: 100%;
    p{
      width: 100%!important;
      margin: 0px;
      line-height: 0px;
      img{
        width: 100%!important;
      }
    }
  }
  /deep/.van-cell__value{
    word-break: keep-all;
    text-align: left;
  }
  /deep/.custom-image .van-empty__image {
    width: 90px;
    height: 90px;
  }
</style>

<script lang="ts">
// @ is an alias to /src
import { 
  Image as VanImage,Empty,Tab,Tabs,Col,
  Row,Divider,Sku,ActionSheet,Icon,
  Cell, CellGroup,GoodsAction, GoodsActionIcon, GoodsActionButton,
  Toast
} from 'vant';
import { Component, Prop, Vue, Watch, Model } from 'vue-property-decorator';
import router from '../router';
import store from '../store/index';
import cartApi from '../api/cart.api';
import collectApi from '../api/collect.api';
import footprintApi from '../api/footprint.api';

Vue.use(VanImage).use(Empty).use(Tabs).use(Tab).use(Col)
.use(Row).use(Divider).use(Sku).use(ActionSheet).use(Icon)
.use(Cell).use(CellGroup).use(GoodsAction).use(GoodsActionIcon).use(GoodsActionButton)
.use(Toast);
@Component
export default class GoodDetailComponent extends Vue {
  private good_id: string = '0';
  private tabActive: number = 0;
  private goodDetail: any = {};
  private showSku: boolean=false;
  private isCollected: boolean = false;
  private selectGood: string = '';
  private collect_id: number = 0;
  private cart_num: number = 0;
  private goods: any =  {
      // 默认商品 sku 缩略图
      picture: 'https://img.yzcdn.cn/1.jpg'
    };
  private initialSku: any = {
    // 键：skuKeyStr（sku 组合列表中当前类目对应的 key 值）
    // 值：skuValueId（规格值 id）
    //s1: '0',

    // 初始选中数量
    selectedNum: 1,
    // 初始选中的商品属性
    // 键：属性id
    // 值：属性值id列表
    selectedProp: {
      
    }
  };
  private sku: any={
    tree: [
    ],
    // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
    list: [
    ],
    price: '1.00', // 默认价格（单位元）
    stock_num: 227, // 商品总库存
    collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
    none_sku: false, // 是否无规格商品
    
    hide_stock: false // 是否隐藏剩余库存
  };
  
  async created(){
    this.good_id=router.currentRoute.params.id;
    store.commit('global/setShowPageLoading',true);
    await store.dispatch('goods/getGoodDetail',this.good_id);
    this.goodDetail=store.getters['goods/goodDetail'].data[0];
    router.currentRoute.meta.navTitle=this.goodDetail.name;
    this.sku.price=this.goodDetail.retail_price;
    this.sku.stock_num=this.goodDetail.goods_number;
    this.sku.none_sku=this.goodDetail.goodsSpecification.length==0?true:false;
    this.goods.picture=this.goodDetail.list_pic_url;

    if(this.goodDetail.goodsSpecification.length!=0){
      const specis: any[]=[];
      for(let item of this.goodDetail.goodsSpecification){
        let speci: any={
          k:'',
          v:[],
          k_s:''
        };
        const v={
          id:item.id,
          name:item.value,
          imgUrl:item.pic_url,
          previewImgUrl:item.pic_url
        };
        let isPush=false;
        if(specis.length>0){
          for(let item1 of specis){
            if(item1.k==item.specification.name){
              item1.v.push(v);
              isPush=true;
              break;
            }
          }
        }
        if(!isPush){
          speci.k=item.specification.name;
          speci.k_s=`s${item.specification.id}`;
          speci.v.push(v);
          specis.push(speci);
        }
      }
      const list: any[]=[];
      for(let item of this.goodDetail.product){
        const obj={
          id: item.id, // skuId，下单时后端需要
          price: item.retail_price*100, // 价格（单位分）
          //s1: '0', // 规格类目 k_s 为 s1 的对应规格值 id
          stock_num: item.goods_number // 当前 sku 组合对应的库存
        };
        const ids=item.goods_specification_ids.split('_');
        for(let id of ids){
          const gs=this.goodDetail.goodsSpecification.filter( s => s.id==id)[0];
          obj[`s${gs.specification.id}`]=gs.id;      
        }
        list.push(obj);
      }
      this.sku.tree=specis;
      this.sku.list=list;
      for(let t of specis){
        this.initialSku[t.k_s]=t.v[0].id;
      }
      this.selectGood=`${this.sku.tree[0].v[0].name}\n${this.sku.tree[1].v[0].name}`;

      this.isCollected=await this.isCollect(this.initialSku.id);
      //console.log(this);
    }else{
      this.sku.collection_id=this.goodDetail.product[0].id;
      this.isCollected=await this.isCollect(this.sku.collection_id);
    }

    const fp=await footprintApi.getFootPrint({
      filter:`goods_id||$eq||${this.goodDetail.id}`
    })
    if(fp.data.length>0){
      footprintApi.delFootPrint(fp.data[0].id);
    }
    footprintApi.addFootPrint(this.goodDetail.id);
    store.commit('global/setShowPageLoading',false);
  }

  private async isCollect(id){
    const res=await collectApi.getCollection({
      filter:`value_id||$eq||${id}`
    });
    if(res.data.length>0){
      this.collect_id=res.data[0].id;
    }
    return res.data.length==0?false:true;
  }

  private onBuyClicked(){
    //console.log(skuData);
    const skuData=(this.$refs.sku as any).getSkuData();
    const p=this.goodDetail.product.filter(v => v.id==skuData.selectedSkuComb.id)[0];
    store.commit('order/setSubmit',{
      totalAmount:p.retail_price * skuData.selectedNum,
      marketAmount:this.goodDetail.market_price * skuData.selectedNum,
      goods:[{
        goods_name:this.goodDetail.name,
        number: skuData.selectedNum,
        retail_price:p.retail_price,
        list_pic_url:this.goodDetail.list_pic_url,
        product_id:p.id
      }]
    });
    router.push({
      path:'/order',
    });
  }

  private onAddCartClicked(){
    const skuData=(this.$refs.sku as any).getSkuData();
    //console.log(skuData);
    cartApi.addCart({
      product_id:skuData.selectedSkuComb.id,
      number:skuData.selectedNum
    });
    this.cart_num+=1;
    Toast('添加成功');
  }

  private async onSelectSku(data: any){
    //console.log(data);
    let goodStr='';
    for(let k in data.selectedSku){
      const t=this.sku.tree.filter(t => t.k_s==k)[0];
      const v=t.v.filter(v => v.id==data.selectedSku[k])[0];
      goodStr+=`${v.name}\n`;
    }
    this.selectGood=goodStr;
    this.isCollected=await this.isCollect(data.selectedSkuComb.id);
  }

  private onClickSelectGood(){
    this.showSku=true;
  }

  private onClickCollect(){
    const skuData=(this.$refs.sku as any).getSkuData();
    if(this.isCollected){
      collectApi.delCollection(this.collect_id);
      this.isCollected=false;
      return;
    }
    collectApi.addCollection(skuData.selectedSkuComb.id);
    this.isCollected=true;
  }

}
</script>
